package io.shqyang.myapplication.time;

import io.shqyang.myapplication.util.DateUtils;

import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TimeManager {

    private static TimeManager instance;
    private Collection<TimeObserver> observers;
    private ScheduledExecutorService service;

    public static TimeManager getInstance() {
        if (instance == null) {
            instance = new TimeManager();
        }
        return instance;
    }

    public void notifyUpdateSecond(String time) {
        for (TimeObserver observer : observers) {
            observer.updateSecond(time);
        }
    }

    public void notifyUpdateSecond(String[] timeArr) {
        for (TimeObserver observer : observers) {
            observer.updateSecond(timeArr);
        }
    }

    private TimeManager() {
        observers = new CopyOnWriteArrayList<>();
        service = new ScheduledThreadPoolExecutor(1);
        Runnable runnable = () -> {
            notifyUpdateSecond(DateUtils.timeNow());
            notifyUpdateSecond(DateUtils.hmsNow());
        };
        service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
    }

    public void addObserver(TimeObserver observer) {
        observers.add(observer);
    }

    public void removeObserver(TimeObserver observer) {
        observers.remove(observer);
    }
}
